package com.spark.gaea.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public final class NetUtil {
	private static final Logger LOG;

	public static List<String> localIPv4() {
		final List<String> localIPs = new ArrayList<String>();
		try {
			final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
			for (final NetworkInterface netint : Collections.list(nets)) {
				if (null != netint.getHardwareAddress()) {
					final List<InterfaceAddress> list = netint.getInterfaceAddresses();
					for (final InterfaceAddress interfaceAddress : list) {
						final String localIP = interfaceAddress.getAddress().getHostAddress();
						if (localIP != null && localIP.length() < 16 && !localIP.contains(":")) {
							localIPs.add(localIP);
						}
					}
				}
			}
		} catch (SocketException e) {
			NetUtil.LOG.warn("\u83b7\u53d6\u672c\u673aIPv4\u5931\u8d25", e);
		}
		return localIPs;
	}

	public static List<String> localIPv6() {
		final List<String> localIPs = new ArrayList<String>();
		try {
			final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
			for (final NetworkInterface netint : Collections.list(nets)) {
				if (null != netint.getHardwareAddress()) {
					final List<InterfaceAddress> list = netint.getInterfaceAddresses();
					for (final InterfaceAddress interfaceAddress : list) {
						final String localIP = interfaceAddress.getAddress().getHostAddress();
						if (localIP != null && localIP.contains(":")) {
							localIPs.add(localIP);
						}
					}
				}
			}
		} catch (SocketException e) {
			NetUtil.LOG.warn("获取本机IPv6失败", e);
		}
		return localIPs;
	}

	public static List<String> localIPs() {
		final List<String> localIPs = new ArrayList<String>();
		try {
			final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
			for (final NetworkInterface netint : Collections.list(nets)) {
				if (null != netint.getHardwareAddress()) {
					final List<InterfaceAddress> list = netint.getInterfaceAddresses();
					for (final InterfaceAddress interfaceAddress : list) {
						final String localIP = interfaceAddress.getAddress().getHostAddress();
						if (localIP != null) {
							localIPs.add(localIP);
						}
					}
				}
			}
		} catch (SocketException e) {
			NetUtil.LOG.warn("\u83b7\u53d6\u672c\u673aIP\u5931\u8d25", e);
		}
		return localIPs;
	}

	static {
		LOG = LoggerFactory.getLogger(NetUtil.class);
	}
}
